package com.oncliedisk.administrator.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;

import com.oncliedisk.administrator.DB.Dao;
import com.oncliedisk.administrator.interfaces.IDataCallback;
import com.oncliedisk.administrator.interfaces.OnDownLoadFinishListener;
import com.oncliedisk.administrator.interfaces.OnFileDownListener;
import com.oncliedisk.administrator.model.EntryModel;
import com.oncliedisk.administrator.model.Event;
import com.vdisk.android.VDiskAuthSession;
import com.vdisk.net.VDiskAPI;
import com.vdisk.net.exception.VDiskException;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/12/7.
 */
public class HttpUtils {
    private static HttpUtils self = null;
    private HttpClient client = null;

    private HttpUtils() {
        //初始化
        client = new DefaultHttpClient();
    }

    /**
     * 获取Http对象
     *
     * @return
     */
    public static HttpUtils getInstance() {
        synchronized (HttpUtils.class) {
            if (self == null) {
                self = new HttpUtils();
            }
            return self;
        }
    }

    public static Bitmap getBitmap(String path) throws IOException {

        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            return bitmap;
        }
        return null;
    }

    /**
     * 根据路径查找本地路径
     *
     * @param model
     * @param onDownLoadFinishListener
     */
    public void getFileLocal(VDiskAPI<VDiskAuthSession> mApi, EntryModel model, OnDownLoadFinishListener onDownLoadFinishListener) {

    }


    public void updateName(Context context, VDiskAPI<VDiskAuthSession> mApi, EntryModel data, String name, OnDownLoadFinishListener onDownLoadFinishListener) {
        new updateTask().execute(mApi, data, onDownLoadFinishListener, name, context);
    }

    public class updateTask extends AsyncTask<Object, Void, Boolean> {
        VDiskAPI<VDiskAuthSession> mApi;
        OnDownLoadFinishListener onDownLoadFinishListener;
        private EntryModel data;
        private String errorInfo; //错误信息
        private String name; //更新的名字
        private List<VDiskAPI.Entry> datal;
        private Context context;

        @Override
        protected Boolean doInBackground(Object... objects) {
            mApi = (VDiskAPI<VDiskAuthSession>) objects[0];
            data = (EntryModel) objects[1];
            onDownLoadFinishListener = (OnDownLoadFinishListener) objects[2];
            name = (String) objects[3];
            context = (Context) objects[4];
            datal = new ArrayList<VDiskAPI.Entry>();
            //重命名复制
            String path = data.path;
            try {
                VDiskAPI.Entry copy = mApi.copy(path, name);
                if (copy != null) {
                    mApi.delete(path);
                    datal.add(copy);
                    return true;
                }
            } catch (VDiskException e) {
                e.printStackTrace();
                errorInfo = e.toString();
                return false;
            }
            return false;
        }


        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean) {
                onDownLoadFinishListener.onSuccess(datal);
            } else {
                onDownLoadFinishListener.onFail(errorInfo);
            }
        }
    }

    /**
     * 获取文件
     *
     * @param contxet
     * @param mApi
     * @param seleced
     * @param onDownLoadFinishListener
     */
    public void getALLFile(Context contxet, VDiskAPI<VDiskAuthSession> mApi, String seleced, OnDownLoadFinishListener onDownLoadFinishListener) {
        new MyTask().execute(contxet, mApi, seleced, onDownLoadFinishListener);
    }

    /**
     * 删除文件
     *
     * @param mApi
     * @param data
     * @param onDownLoadFinishListener
     */
    public void deleteFile(Context context, VDiskAPI<VDiskAuthSession> mApi, List<EntryModel> data, OnDownLoadFinishListener onDownLoadFinishListener) {
        new deleteTask().execute(mApi, data, onDownLoadFinishListener);
    }

    public class deleteTask extends AsyncTask<Object, Void, Boolean> {
        VDiskAPI<VDiskAuthSession> mApi;
        OnDownLoadFinishListener onDownLoadFinishListener;
        private List<EntryModel> data;
        private String errorInfo; //错误信息

        @Override
        protected Boolean doInBackground(Object... objects) {
            mApi = (VDiskAPI<VDiskAuthSession>) objects[0];
            data = (List<EntryModel>) objects[1];
            onDownLoadFinishListener = (OnDownLoadFinishListener) objects[2];
            for (EntryModel model : data) {
                try {
                    VDiskAPI.Entry delete = mApi.delete(model.path);
                } catch (VDiskException e) {
                    e.printStackTrace();
                    errorInfo = e.toString();
                    return false;
                }
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean) {
                onDownLoadFinishListener.onSuccess(null);
            } else {
                onDownLoadFinishListener.onFail(errorInfo);
            }
        }
    }


    public class MyTask extends AsyncTask<Object, Void, Boolean> {
        VDiskAPI<VDiskAuthSession> mApi;
        Context contxet;
        String seleced;
        OnDownLoadFinishListener onDownLoadFinishListener;
        private List<VDiskAPI.Entry> data;
        private String errorInfo; //错误信息

        @Override
        protected Boolean doInBackground(Object... lists) {
            contxet = (Context) lists[0];
            mApi = (VDiskAPI<VDiskAuthSession>) lists[1];
            seleced = (String) lists[2];
            onDownLoadFinishListener = (OnDownLoadFinishListener) lists[3];
            //这是根据JSON字符串返回对象，再进行存储数据库
            //这是网盘API的方式查询数据
            try {
                VDiskAPI.Entry metadata = mApi.metadata(seleced, null, true, false);
                if (metadata != null) {
                    boolean b = Dao.getInstance(contxet).saveFile(seleced, metadata.contents, mApi);
                    if (b) {
                        //存储成功
                        if(metadata.contents.size()>0){
                            this.data = metadata.contents;
                        }
                        return true;
                    } else {
                        errorInfo = "存储失败";
                    }
                }
            }
            catch (VDiskException e) {
                errorInfo = FileUtils.getErrorByStr(e.toString());
                return false;
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean) {
                onDownLoadFinishListener.onSuccess(data);
            } else {
                onDownLoadFinishListener.onFail(errorInfo);
            }
        }
    }

    /**
     * 检查当前网络是否可用
     *
     * @param
     * @return
     */

    public static boolean isNetworkAvailable(Context activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public void rename(IDataCallback handler, int requestCode, String parentPath, String oldName, String newName,VDiskAPI<VDiskAuthSession> mApi,Bundle session) {
        new RenameTask(handler,requestCode, parentPath, oldName, newName,mApi,session).execute();
    }
    private class RenameTask extends AsyncTask<Void, Void, Event> {
        IDataCallback handler;
        String parentPath;
        String oldName;
        String newName;
        VDiskAPI<VDiskAuthSession> mApi;
        Bundle session;
        Event event = new Event();
        public RenameTask(IDataCallback handler,int requestCode, String parentPath, String oldName, String newName,VDiskAPI<VDiskAuthSession> mApi,Bundle session) {
            this.handler = handler;
            this.parentPath = parentPath;
            this.oldName = oldName;
            this.newName = newName;
            this.session = session;
            this.mApi = mApi;
            event.requestCode = requestCode;
        }


        @Override
        protected Event doInBackground(Void... voids) {
            try {
                parentPath = removePathLastSlice(parentPath);
                String oldPath = parentPath
                        + (parentPath.equals("/") ? "" : "/") + oldName;
                String newPath = parentPath
                        + (parentPath.equals("/") ? "" : "/") + newName;
                VDiskAPI.Entry entry = mApi.move(oldPath, newPath);
                event.data = entry;
            } catch (VDiskException e) {
                event.e = e;
            }

            return event;
        }
        @Override
        protected void onPostExecute(Event event) {
            handler.handleServiceResult(event, session);
        }
    }
    public static String removePathLastSlice(String path) {
        if (path == null) {
            return null;
        }

        if (path.endsWith("/") && !path.equals("/")) {
            return path.substring(0, path.length() - 1);
        }

        return path;
    }


    public void downImageTask(String path,OnFileDownListener onFileDownListener){
        new downImageTask().execute(path,onFileDownListener);
    }
    /**
     * 开启线程，对图片进行下载存入数据库，并且重新获取目录信息
     */
    public class downImageTask extends AsyncTask<Object, Void, Boolean> {

        private String path;
        private VDiskAPI<VDiskAuthSession> mApi;
        private String downPath;
        private String localPath;
        private ImageView img;
        private Context context;
        private OnFileDownListener onFileDownListener;
        @Override
        protected Boolean doInBackground(Object... params) {
            path = (String) params[0];
            onFileDownListener = (OnFileDownListener) params[1];
            mApi = OnlineUtils.getMapi(context);
            FileOutputStream mFos = null;
            try {
                String cachePath = Environment.getExternalStorageDirectory()
                        .getAbsolutePath() + "/VDisk_SDK_cache/" + path;
                File downloadDirFile = mApi.createDownloadDirFile(cachePath);
                try {
                    mFos = new FileOutputStream(downloadDirFile, false);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                VDiskAPI.VDiskFileInfo thumbnail = mApi.getThumbnail(path, mFos, VDiskAPI.ThumbSize.ICON_640x480, null);
                //执行更新本图片数据操作
                    Log.i("info", "成功吧下载地址添加到数据库");
                    //说明获取成功，成功填入数据库
                    downPath = thumbnail.getDownloadURL();
                    localPath = cachePath;
                    return true;
            } catch (VDiskException e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean) {
                onFileDownListener.onFail(downPath);
            }else{

            }
        }
    }

}
